import com.alibaba.fastjson.JSON;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import User.UserDTO;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import User.MessageDTO;
import java.util.ArrayList;
import java.util.List;
import httpclient.QuickStart;

@WebServlet(urlPatterns = {"/Login_Check"})
public class Login_Check extends HttpServlet{


    //判断登录用户信息是否存在
    protected static MessageDTO login_exit(String name, String password)
    {
        MessageDTO message=null;
        String line=null;
        try{
            BufferedReader bufferedReader=new BufferedReader((new FileReader("src/main/a.txt")));
            while((line=bufferedReader.readLine())!=null)
            {
                String[] str = line.split(" ");
                if (str[0].equals(name)&&str[2].equals(password)) {
                    message=new MessageDTO(str[0],str[1],str[2],str[3],str[4]);
                    bufferedReader.close();;
                    return message;
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到");
        } catch (IOException e) {
            System.out.println("读取失败");
        }
        return message;
    }

    protected void login_check(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException
    {
        String loginname = req.getParameter("loginname");
        String loginpassword = req.getParameter("loginpassword");
        MessageDTO message=login_exit(loginname,loginpassword);
        if(message!=null)
        {
            req.getSession().setAttribute("LocalUser",message);
            resp.sendRedirect("userinfo.jsp");
        }
        else{
            System.out.println("该用户不存在，请先注册");
            resp.sendRedirect("error.jsp");
        }

    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        login_check(req,resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

}